﻿/*
 * devicemgr.cpp
 *
 *  Created on: 2017年11月30日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_SCADA DM_API_EXPORT

#include <dm/scada/devicemgr.hpp>
#include <dm/scada/scadainfo.hpp>
#include <dm/scada/devicestate.hpp>

namespace dm{
namespace scada{

CDeviceMgr::CDeviceMgr( CScada& scada ):CScada(scada),
		m_cfg(scada.deviceInfos(),scada.info()->deviceCount()){
}

CDeviceMgr& CDeviceMgr::ins(){
	static CDeviceMgr i(CScada::ins());
	return i;
}

bool CDeviceMgr::setDesc( const index_t& idx,const char* str ){
	SDeviceInfo* p = m_cfg.at(idx);
	if( p ){
		p->desc = str;
		return true;
	}else
		return false;
}

/**
 * 获取设备状态对应的设备索引
 * @param state
 * @return
 */
index_t CDeviceMgr::indexOfState( const CDeviceState* s )const{
	if( s<deviceStates() )
		return Idx_Inv;
	index_t rt = s-deviceStates();
	if( rt>=size() )
		return Idx_Inv;
	return rt;
}

/**
 * 获取设备状态对应的设备索引
 * @param state
 * @return
 */
index_t CDeviceMgr::indexOfState( const volatile CDeviceState* s )const{
	if( s<deviceStates() )
		return Idx_Inv;
	index_t rt = s-deviceStates();
	if( rt>=size() )
		return Idx_Inv;
	return rt;
}

/**
 * 获取设备状态
 * @param idx
 * @return
 */
const CDeviceState* CDeviceMgr::state( const index_t& idx )const{
	if( idx<0 || idx>=size() )
		return NULL;
	return deviceStates()+idx;
}

/**
 * 获取设备状态
 * @param idx
 * @return
 */
CDeviceState* CDeviceMgr::state( const index_t& idx ){
	if( idx<0 || idx>=size() )
		return NULL;
	return deviceStates()+idx;
}

/**
 * 设备是否在线
 * @param idx
 * @return
 */
bool CDeviceMgr::isAlive( const index_t& idx )const{
	const CDeviceState* p = state(idx);
	return p?p->isAlive():false;
}

/**
 * 输出设备信息
 * @param idx
 * @param ostr
 */
void CDeviceMgr::print( const index_t& idx,std::ostream& ostr )const{
	const SDeviceInfo* p = info(idx);
	if( p ){
		ostr <<"ID:"<<p->id
				<<" 名字:"<<p->name.c_str()
				<<" 描述:"<<p->desc.c_str()
				<<" 状态量:"<<p->sizeOfStatus<<"@"<<p->posOfStatus
				<<" 离散量:"<<p->sizeOfDiscrete<<"@"<<p->posOfDiscrete
				<<" 测量量:"<<p->sizeOfMeasure<<"@"<<p->posOfMeasure
				<<" 累计量:"<<p->sizeOfCumulant<<"@"<<p->posOfCumulant
				<<" 远控:"<<p->sizeOfTeleCtl<<"@"<<p->posOfTeleCtl
				<<" 参数:"<<p->sizeOfPara<<"@"<<p->posOfPara
				<<" 动作:"<<p->sizeOfAction<<"@"<<p->posOfAction;
	}else{
		ostr <<"无效索引("<<idx<<")";
	}
}

}
}


